<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col> <el-button type="primary"> 添加用户 </el-button></el-col>
      </el-row>
      <el-table :data="RolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index == 0 ? 'btop' : '', 'venter']"
              v-for="(item, index) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRoles(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index1 === 0 ? '' : 'btop', 'venter']"
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRoles(scope.row, item1.id)"
                      type="success"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      type="warning"
                      @close="removeRoles(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>

                  <!-- <el-col
                    :span="18"
                    v-for="item2 in item1.children"
                    :key="item2.id"
                  >
                    <el-tag type="warning">{{ item2.authName }}</el-tag>
                  </el-col> -->
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 修改用户 -->
            <el-button size="mini" type="primary" icon="el-icon-edit">
              编辑</el-button
            >
            <!-- 删除用户 -->
            <el-button size="mini" type="danger" icon="el-icon-delete">
              删除</el-button
            >
            <!-- 角色 -->

            <el-button
              @click="showSetRightDialog(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
            >
              分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框-->

    <el-dialog
      @close="setRightsDialogClosed"
      title="提示"
      :visible.sync="showSetRightDialogVisable"
      width="50%"
    >
      <!-- 树形结构区域 -->
      <el-tree
        node-key="id"
        :props="rightsProps"
        default-expand-all
        :data="rightList"
        show-checkbox
        :default-checked-keys="defaulKeys"
        ref="treeRef"
      >
      </el-tree>

      <span slot="footer">
        <el-button @click="showSetRightDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //权限列表
      RolesList: [],
      // 分配权限的对话框展示与隐藏
      showSetRightDialogVisable: false,

      //当前分配角色的id
      roleId: 0,
      //树形列表数据
      rightList: [],
      //树形结构属性对象
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      //属性结构默认展示的权限
      defaulKeys: []

    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取角色信息
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message({ showClose: true, message: '获取数据失败', type: 'error' })

      }
      this.RolesList = res.data
      // console.log(this.RolesList)

    },
    async removeRoles(role, rightId) {
      // console.log("aa")
      const rolesConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (rolesConfirm != 'confirm') {
        return this.$message({ showClose: true, message: '已取消删除', type: 'info' })
      }

      // 发送删除的请求
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

      if (res.meta.status != 200) {
        return this.$message({ showClose: true, message: '删除权限失败', type: 'error' })

      }
      //重新调用这个方法会发生整个页面的重新渲染
      // this.getRolesList()
      // role.children = res.data
      console.log(res);
      role.children = res.data


    },
    //分配权限的对话框的展示
    async showSetRightDialog(role) {

      this.roleId = role.id

      //请求树形结构的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status != 200) {
        return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      }


      console.log(res);
      this.rightList = res.data
      this.getLeafKeys(role, this.defaulKeys)
      this.showSetRightDialogVisable = true
    },

    //递归函数查找到三级权限默认的id
    getLeafKeys(node, arr) {

      //三级权限没有chlidren属性 
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))



    },
    //分配权限的对话框关闭时 清空默认数组权限
    setRightsDialogClosed() {
      this.defaulKeys = []
    },
    //为角色分配权限
    async allotRights() {
      //得到所有全选中的节点和半选中的节点
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()

      ]

      const idStr = keys.join(',')
      // console.log(idStr);
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })

      if (res.meta.status != 200) {
        return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      }
      this.getRolesList()
      this.showSetRightDialogVisable = false

      this.$message({ showClose: true, message: res.meta.msg, type: 'success' })

      //隐藏对话框





    }


  }


}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.btop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.venter {
  display: flex;
  align-items: center;
}
</style>